const LogService = require('../services/log.service')
const ReportService = require('../services/report.service')
const PlaceService = require('../services/place.service')
const MessageService = require('../services/message.service')
const logger = require('../utils/logger')

const logService = new LogService()
const reportService = new ReportService()
const placeService = new PlaceService()
const messageService = new MessageService()

module.exports = async function checkDailyReports () {
  console.log('start checkDailyReports schedule')
  logger.info('start checkDailyReports schedule')
  const endTime = +new Date(new Date().format('yyyy-MM-dd 00:00:00'))
  // const startTime = +endTime - 86400000
  const config = require('../../config.json')
  const maxReportInterval = (parseInt(config.maxReportInterval) || 1)
  const places = await placeService.findAll({ status: 'filed', pageSize: 9999999 })
  logger.info('filed places length ', places.data.length)
  places.data.forEach(async p => {
    const latestReports = await reportService.findAll({ pageSize: 1, place: p._id.toString() })
    const latestReportDays = Math.ceil((latestReports.data.length && (endTime - new Date(latestReports.data[0].submitDate)) || 0) / 86400000)
    const shouldWarning = latestReportDays > maxReportInterval
    logger.info('latest reports', latestReports.data, latestReportDays, shouldWarning)
    logService.addOne({
      type: shouldWarning ? 'report_abnormal' : 'report_normal',
      ref: p._id,
      note: latestReportDays
    })
    if (shouldWarning) {
      let message = '请上报每日消防状态'
      messageService.addOne({
        type: 'report_warning',
        ref: p.registration,
        note: message
      })
      logger.info('place need warning ', p)
    }
  })

}